package com.zyl.blog.common.execute;

import com.zyl.blog.common.utils.Extreme.LogUtil;
import io.micrometer.common.lang.NonNullApi;
import jakarta.validation.constraints.NotNull;

import java.time.Duration;
import java.time.Instant;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.*;

/**
 * @version v1.0
 * @ProjectName: Personal_Blog_Server
 * @Package: com.zyl.blog.common.execute
 * @ClassName: LoggingVirtualThreadExecutor
 * @Description: 带日志的虚拟线程池包装类（完整实现）
 * @Author FinalFantasy
 * @Date 2025/8/11-16:35
 */
@NonNullApi
public class LoggingVirtualThreadExecutor implements ExecutorService {
    private final ExecutorService delegate;
    private final String poolName;

    public LoggingVirtualThreadExecutor(String poolName) {
        this.poolName = poolName;
        this.delegate = Executors.newVirtualThreadPerTaskExecutor();
    }

    // 核心执行方法
    @Override
    public void execute(Runnable command) {
        delegate.execute(command);
    }

    // 关闭相关方法
    @Override
    public void shutdown() {
        delegate.shutdown();
    }

    @Override
    public List<Runnable> shutdownNow() {
        return delegate.shutdownNow();
    }

    @Override
    public boolean isShutdown() {
        return delegate.isShutdown();
    }

    @Override
    public boolean isTerminated() {
        return delegate.isTerminated();
    }

    @Override
    public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
        return delegate.awaitTermination(timeout, unit);
    }

    // 提交任务相关方法
    @Override
    public <T> Future<T> submit(Callable<T> task) {
        return delegate.submit(task);
    }

    @Override
    public <T> Future<T> submit(Runnable task, T result) {
        return delegate.submit(task, result);
    }

    @Override
    public Future<?> submit(Runnable task) {
        return delegate.submit(task);
    }

    // 批量执行任务相关方法
    @Override
    public <T> List<Future<T>> invokeAll(@NotNull Collection<? extends Callable<T>> tasks)
            throws InterruptedException {
        return delegate.invokeAll(tasks);
    }

    @Override
    public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
                                         long timeout, TimeUnit unit)
            throws InterruptedException {
        return delegate.invokeAll(tasks, timeout, unit);
    }

    @Override
    public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
            throws InterruptedException, ExecutionException {
        return delegate.invokeAny(tasks);
    }

    @Override
    public <T> T invokeAny(Collection<? extends Callable<T>> tasks,
                           long timeout, TimeUnit unit)
            throws InterruptedException, ExecutionException, TimeoutException {
        return delegate.invokeAny(tasks, timeout, unit);
    }

    /**
     * 增强的close方法，添加详细日志
     */
    @Override
    public void close() {
        LogUtil.info("[{}] 开始关闭虚拟线程池", poolName);
        Instant start = Instant.now();

        try {
            // 调用虚拟线程池的close()方法
            if (delegate instanceof AutoCloseable autoCloseable) {
                autoCloseable.close();
                LogUtil.info("[{}] 已触发虚拟线程池关闭", poolName);
            }

            // 等待任务完成（设置超时）
            boolean terminated = awaitTermination(30, TimeUnit.SECONDS);
            Duration cost = Duration.between(start, Instant.now());

            if (terminated) {
                LogUtil.info("[{}] 所有任务完成，关闭成功，耗时: {}ms",
                        poolName, cost.toMillis());
            } else {
                LogUtil.warn("[{}] 等待30秒后仍有未完成任务", poolName);
            }
        } catch (InterruptedException e) {
            LogUtil.error("[{}] 关闭被中断", e, poolName);
            Thread.currentThread().interrupt(); // 保留中断状态
        } catch (Exception e) {
            LogUtil.error("[{}] 关闭发生异常", e, poolName);
        } finally {
            LogUtil.info("[{}] 关闭流程结束", poolName);
        }
    }
}
